package com.example.service;

import com.example.entity.OrganizationBranch;
import com.example.entity.OrganizationMember;
import com.example.entity.SelectMemberDTO;
import com.example.entity.StudentInfo;
import com.example.exception.CustomException;
import com.example.mapper.OrganizationBranchMapper;
import com.example.mapper.OrganizationMemberMapper;
import com.example.mapper.StudentInfoMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * 组织成员表业务处理
 **/
@Service
public class OrganizationMemberService {

    @Resource
    private OrganizationMemberMapper organizationMemberMapper;
    @Resource
    private OrganizationBranchMapper organizationBranchMapper;

    @Resource
    private StudentInfoMapper studentInfoMapper;


    /**
     * 新增成员
     */
    @Transactional
    public void add(OrganizationMember member, Long leaderId) {
        validateBranchPermission(leaderId, member.getBranchId());
        // 其他业务逻辑...
        Integer orgType = member.getOrgType();
        Integer memberStatus = member.getMemberStatus();
        Long userId = member.getUserId();
        if(studentInfoMapper.selectByUserId(userId) != null){
            if (orgType == 2){//是团员
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setUserId(userId);
                studentInfo.setPoliticalStatus(2);
            }else if(orgType == 1 && memberStatus == 1){//是预备党员
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setUserId(userId);
                studentInfo.setPoliticalStatus(3);
            }else if( orgType == 1 && memberStatus == 2){//是正式党员
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setUserId(userId);
                studentInfo.setPoliticalStatus(4);
            }
        }
        organizationMemberMapper.insert(member);
    }

    /**
     * 更新成员
     */
    @Transactional
    public void updateById(OrganizationMember member, Long leaderId) {
        validateBranchPermission(leaderId, member.getBranchId());
        Integer orgType = member.getOrgType();
        Integer memberStatus = member.getMemberStatus();
        Long userId = member.getUserId();
        if(studentInfoMapper.selectByUserId(userId) != null){
            if (orgType == 2){//是团员
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setUserId(userId);
                studentInfo.setPoliticalStatus(2);
            }else if(orgType == 1 && memberStatus == 1){//是预备党员
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setUserId(userId);
                studentInfo.setPoliticalStatus(3);
            }else if( orgType == 1 && memberStatus == 2){//是正式党员
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setUserId(userId);
                studentInfo.setPoliticalStatus(4);
            }
        }
        organizationMemberMapper.updateById(member);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        organizationMemberMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            organizationMemberMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(OrganizationMember organizationMember) {
        organizationMemberMapper.updateById(organizationMember);
    }

    /**
     * 根据ID查询
     */
    public OrganizationMember selectById(Integer id) {
        return organizationMemberMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<OrganizationMember> selectAll(OrganizationMember organizationMember) {
        return organizationMemberMapper.selectAll(organizationMember);
    }

    /**
     * 分页查询
     */
    public PageInfo<OrganizationMember> selectPage(OrganizationMember organizationMember, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OrganizationMember> list = organizationMemberMapper.selectAll(organizationMember);
        return PageInfo.of(list);
    }

    /**
     * 根据用户ID查询组织成员信息
     */
    public OrganizationMember getByUserId(Long userId) {
        return organizationMemberMapper.getByUserId(userId);
    }

    public PageInfo<OrganizationMember> selectMember(SelectMemberDTO selectMemberDTO, Integer pageNum, Integer pageSize) {
        // 1. 参数校验
        if (selectMemberDTO.getLeaderId() == null) {
            //log.error("leaderId不能为空");
            throw new RuntimeException("参数错误");
        }

        // 2. 查询该领导管理的所有支部ID
        List<Long> branchIds = organizationBranchMapper.selectByLeaderId(selectMemberDTO.getLeaderId());
        if (CollectionUtils.isEmpty(branchIds)) {
            //log.warn("未查询到领导人[{}]的支部信息", selectMemberDTO.getLeaderId());
            return new PageInfo<>(Collections.emptyList());
        }
        //log.info("领导人[{}]管理的支部ID: {}", selectMemberDTO.getLeaderId(), branchIds);

        // 3. 设置支部IDs到查询条件
        selectMemberDTO.setBranchIds(branchIds);

        // 4. 分页查询
        PageHelper.startPage(pageNum, pageSize);
        List<OrganizationMember> list = organizationMemberMapper.selectMember(selectMemberDTO);

        return new PageInfo<>(list);
    }


    /**
     * 验证用户是否有权限操作该支部
     */
    private void validateBranchPermission(Long leaderId, Long branchId) {
        OrganizationBranch branch = organizationBranchMapper.selectById(branchId);
        if (branch == null) {
            throw new CustomException("支部不存在");
        }
        if (!leaderId.equals(branch.getLeaderId())) {
            throw new CustomException("您没有权限操作该支部");
        }
    }

}